#pragma once

#include <string>
#include <mutex>

using namespace std;

#include "topdbs_cross_platform.hpp"

#define TOPDBS_DEBUG_LOG         "topdbs.log"
#define TOPDBS_ERROR_LOG         "topdbs.err"
#define TOPDBS_DEUBG_ENV_TAG     "TOPDBS_LOGLEVEL"

namespace topdbs
{
    typedef
    enum eDBSLogLevel
    {
        DBS_TRACE = 0,
        DBS_DEBUG,
        DBS_INFO,
        DBS_WARN,
        DBS_ERROR
    }eDBSLogLevel_t;

    class TOPDBS_API topdbs_log
    {
    private:
        FILE* m_fpDebug;
        FILE* m_fpError;
        
        topdbs_log() = default;
        topdbs_log(const topdbs_log& ) = default;

        void rotate();

        static topdbs_log* m_instance;
        static std::mutex m_lock;
        static bool m_status;

        class AutoRelease
        {
            public:
            ~AutoRelease()
            {
                if (topdbs_log::m_instance)
                {
                    std::lock_guard<std::mutex> _lock(topdbs_log::m_lock);
                    if (topdbs_log::m_instance)
                    {
	                    topdbs_log::m_instance->close();
	                    delete topdbs_log::m_instance;
	                    topdbs_log::m_instance = nullptr;
                    }
                }
            };
        };	    
        static AutoRelease m_release;
    public:
        int openlog();
        int close();
        int writelog(const char* file,const char* function,int line,int level,const char* fmt,...);
        int writelog(int dbsLevel,int level,const char* data);	
        static topdbs_log* rootLog();			
    };
#ifdef WIN32
    #define dbslog(Level,Fmt, ...) topdbs_log::rootLog()->writelog(__FILE__, __FUNCTION__, __LINE__,Level,Fmt,__VA_ARGS__);
#else
    #define dbslog(Level,Fmt, ...) topdbs_log::rootLog()->writelog(__FILE__, __FUNCTION__, __LINE__,Level,Fmt,##__VA_ARGS__);
#endif    
}
